<template>
  <div style="padding: 10px 20px;background-color: #ffffff">
    <el-link type="primary" @click="barkList">返回列表</el-link>
  </div>
  <FormCreate :rule="rule.data" :option="options" v-model="formData" v-model:api="fApi"></FormCreate>
  <div style="margin-left: 126px;margin-top: 30px;display: flex;align-items: center">
    <div v-if="!editTow">
      <el-button type="success" @click="submit('1')">存草稿</el-button>
      <el-button type="primary" @click="submit('0')">提交</el-button>
    </div>
    <div v-else>
      <el-button type="primary" @click="submit()">保存</el-button>
    </div>
    <el-button style="margin-left: 10px" type="info" @click="cancel">取消</el-button>
  </div>
</template>

<script setup>
import {useRoute,useRouter} from "vue-router";
import {
  _addPerson, _carNumberCheck, _getAreaByUserId,
  _getFormInfoById,
  _getOptionListByName,
  _getPersonId,
  _idCodeSearch,
  _updatePerson
} from "../../http/api.js";
import {ElLoading, ElMessage} from "element-plus";
import formCreate from "@form-create/element-ui";
import {ref,reactive} from "vue";
import Validator from 'validator';
import {addField} from "../../utils/field.js";
import { debounce, throttle } from 'lodash'


const route = useRoute();
const router = useRouter();

const loginId = sessionStorage.getItem('loginId');
const exhibitionId = sessionStorage.getItem('projectId');

if(!loginId||!exhibitionId) {
  ElMessage({message: '操作异常', type: 'error' });
  localStorage.clear();
  sessionStorage.clear();
  router.replace({ path: '/'})
}
const templateId = route.query.templateId; // 模板id
const personId = route.query.personId; // 数据id
const type = route.query.type; // 证件类型标志
const editTow = route.query.editTow; // 证件类型标志
if(!templateId||!type) {
  ElMessage({message: '操作异常', type: 'error' });
  localStorage.clear();
  sessionStorage.clear();
  router.replace({ path: '/'})
}
//获取 formCreate 组件
const FormCreate = formCreate.$form();
const fApi = ref({});
const formData = ref({});
const options = ref({
  //表单提交事件
  submitBtn: false,
  form:{
    labelWidth: '200px'
  }
});
// 选择的字段
const rule = reactive({
  data:[]
})
// 返回列表
const barkList = () => {
  router.go(-1)
}
// 获取模板字段详情
const getInfoById = () => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'})
  _getFormInfoById(templateId)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let item = res.data.data;
          let fieldTemplateList = item.fieldTemplateList;
          let types = [];
          for (let i = 0; i < fieldTemplateList.length; i++) {
            let item = fieldTemplateList[i];
            if(item.fieldType === 'select' || item.fieldType === 'radio') {
              types.push(item.fieldName)
            }
          }
          getAreaByUserId(loginId,item.cert.id,types.toString(),fieldTemplateList)
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
        ElMessage({message: '网络异常', type: 'error' });
      })
}
if(templateId) {
  getInfoById()
}
// 获取字段列表二级选项
const getOptionListByName = (type,list,areaList) => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'})
  _getOptionListByName(type)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let arr = res.data.data;
          console.log(arr);
          for (let j = 0; j < arr.length; j++) {
            for (let i = 0; i < list.length; i++) {
              if(list[i].fieldName === 'carArea') {
                let arrList = [];
                areaList.forEach(v => {
                  arrList.push({ label: v.areaName,value: v.areaName })
                })
                list[i]['optionsData'] = arrList;
              }else {
                if(arr[j].fieldType === list[i].fieldName) {
                  let listData = arr[j].list||[];
                  let arrList = [];
                  listData.forEach(v => {
                    arrList.push({ label: v.name,value: v.name })
                  })
                  list[i]['optionsData'] = arrList;
                }
              }
            }
          }
          list.forEach(v => {
            let config = addField(v.fieldType,{field:v.fieldName,title:v.notes},v.optionsData);
            config.effect.required = (v.isFlag === '0');
            rule.data.push(config)
          })
          fApi.value.refreshOptions();
          if(personId) {
            getPersonId()
          }
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
        ElMessage({message: '网络异常', type: 'error' });
      })
}
// g根据用户id获取用户下区域
const getAreaByUserId = (userId,certId,types,fieldTemplateList) => {
  _getAreaByUserId({userId,certId})
      .then(res => {
        console.log(res);
        if(res.data.ok) {
          let areaList = res.data.data;
          getOptionListByName(types,fieldTemplateList,areaList)
        }
      })
      .catch(err => {
        console.log(err);
      })
}

// 获取数据详情
const getPersonId = () => {
  _getPersonId(personId)
      .then(res => {
        console.log(res);
        if(res.data.ok) {
          let item = res.data.data.value;
          if(item.cardTypeOne) {
            item['cardTypeOneA'] = item.cardTypeOne;
          }
          if(item.cardTypeTwo) {
            item['cardTypeTwoA'] = item.cardTypeTwo;
          }
          console.log(item);

          // let datePickers = item.datePickers?item.datePickers[0]?item.datePickers:[]:[];
          // let rule = [];
          // datePickers.forEach((v,i) => {
          //   rule.push({
          //     type: 'TimePicker',
          //     title: v,
          //     field:v,
          //     props:{
          //       isRange:true,
          //       valueFormat:'HH:mm:ss'
          //     }
          //   })
          // })
          //
          // let times = fApi.value.getRule('times');
          // console.log(times);
          // times.props.rule = rule;
          // if(!item.datePickersEnd || !item.datePickersStart) {
          //   item['datePickersEnd'] = '';
          //   item['datePickersStart'] = '';
          // }
          let times = item.times;
          if(times && times.length) {

          }else{
            item['times'] = []
          }
          fApi.value.coverValue({ ... item });
          fApi.value.refreshOptions();
        }
      })
      .catch(err => {
        console.log(err);
      })
}


// 提交数据
const submit = debounce((state) => {
  fApi.value.submit((formData) => {
    console.log(formData);
    let address1 = formData.address1||'';
    let address2 = formData.address2||'';
    let address3 = formData.address3||'';
    let address4 = formData.address4||'';
    let address5 = formData.address5||'';
    let address6 = formData.address6||'';
    let address7 = formData.address7||'';
    let address8 = formData.address8||'';
    let address9 = formData.address9||'';
    let address10 = formData.address10||'';
    if(address1) formData.address1 = address1.toString().replaceAll(',','-');
    if(address2) formData.address2 = address2.toString().replaceAll(',','-');
    if(address3) formData.address3 = address3.toString().replaceAll(',','-');
    if(address4) formData.address4 = address4.toString().replaceAll(',','-');
    if(address5) formData.address5 = address5.toString().replaceAll(',','-');
    if(address6) formData.address6 = address6.toString().replaceAll(',','-');
    if(address7) formData.address7 = address7.toString().replaceAll(',','-');
    if(address8) formData.address8 = address8.toString().replaceAll(',','-');
    if(address9) formData.address9 = address9.toString().replaceAll(',','-');
    if(address10) formData.address10 = address10.toString();

    if(formData.datePickersStart && formData.datePickersEnd) {
      let start = new Date(formData.datePickersStart).getTime();
      let end = new Date(formData.datePickersEnd).getTime();
      if(start > end) return ElMessage({message: '使用结束日期不能小于开始日期', type: 'warning' });
    }

    let params = {
      value: JSON.stringify(formData),
      // json:formData,
      templateId,
      state,
      userId: loginId,
      exhibitionId: exhibitionId,
      type
      // oneLevelState: 0,
      // twoLevelState: 0,
      // threeLevel: 0,
    }
    if(!state) {
      delete params.state;
    }
    console.log(params);
    if(personId) {
      const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)',})
      params['id'] = personId;
      delete params.userId;
      delete params.exhibitionId;
      _updatePerson(params)
          .then(res => {
            console.log(res);
            loading.close();
            if(res.data.ok) {
              ElMessage({message: '更新成功', type: 'success' });
              router.go(-1)
            }else{
              ElMessage({message: res.data.msg, type: 'error' });
            }
          })
          .catch(err => {
            console.log(err);
            loading.close();
            ElMessage({message: '网络异常，请重试', type: 'error' });
          })
    }else {
      const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)',})
      _addPerson(params)
          .then(res => {
            console.log(res);
            loading.close();
            if(res.data.ok) {
              ElMessage({message: '添加成功', type: 'success' });
              router.go(-1)
            }else{
              ElMessage({message: res.data.msg, type: 'error' });
            }
          })
          .catch(err => {
            console.log(err);
            loading.close();
            ElMessage({message: '网络异常，请重试', type: 'error' });
          })
    }
  })
},500)

// 取消
const cancel = () => {
  router.go(-1)
}
</script>

<style scoped lang="scss">

</style>